import 'dart:convert';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_terminal_list_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/change_to_diy_or_module_page_event.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_building_index_terminal_settings_event.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/ui/building_index/show_set_module_type_bubble_event.dart';
import 'package:e_reception_flutter/ui/common/update_diy_center_info_event.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../app_main.dart';
import 'create_building_index_response_bean.dart';


class BuildingIndexViewModel extends BaseViewModel {

  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ValueNotifier<BuildingIndexDetailBean> buildingIndexDetailValueNotifier;
  ValueNotifier<BuildingIndexTerminalDataBean> buildingIndexTerminalValueNotifier;

  BuildingIndexViewModel(BaseState<StatefulWidget> state)
      : super(state){
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    buildingIndexDetailValueNotifier = ValueNotifier(null);
    buildingIndexTerminalValueNotifier = ValueNotifier(null);
  }

  ///创建水牌
  //upflg 是否有地上01有 00无
  //dflg 是否有地下01有 00无
  void createBuildingIndex(BuildContext context, String moduleId, String title,
      String upflg, String dflg, Function(String) createSuccess,
      {int upStart, int upEnd, int downStart, int downEnd,}){
    if(StringUtils.isEmpty(moduleId)){
      return;
    }
    loading(true, msg: "正在创建");
    VgHttpUtils.get(NetApi.CREATE_BUILDING_INDEX, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "syswid": moduleId ?? "",
      "wtitle": title ?? "",
      "upflg": upflg ?? "",
      "dflg": dflg ?? "",
      "usnum": upStart ?? "",
      "uenum": upEnd ?? "",
      "dsnum": downStart ?? "",
      "denum": downEnd ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          CreateBuildingIndexResponseBean bean =
          CreateBuildingIndexResponseBean.fromMap(val);
          if(bean != null && bean.success && bean.data != null && StringUtils.isNotEmpty(bean.data.comwid)){
            createSuccess.call(bean.data.comwid);
            loading(false);
            VgToastUtils.toast(AppMain.context, "创建成功");
            VgEventBus.global.send(new RefreshDiyPageEvent());
            //更新制作中心显示
            VgEventBus.global.send(new UpdateDiyCenterInfoEvent());
          }else{
            VgToastUtils.toast(AppMain.context, "创建失败");
          }

        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///编辑水牌
  //upflg 是否有地上01有 00无
  //dflg 是否有地下01有 00无
  void editBuildingIndex(BuildContext context, String buildingIndexId, String title,
      String upflg, String dflg,
      {int upStart, int upEnd, int downStart, int downEnd,}){
    if(StringUtils.isEmpty(buildingIndexId)){
      return;
    }
    loading(true, msg: "请稍候");
    VgHttpUtils.get(NetApi.EDIT_BUILDING_INDEX, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id": buildingIndexId ?? "",
      "wtitle": title ?? "",
      "upflg": upflg ?? "",
      "dflg": dflg ?? "",
      "usnum": upStart ?? 0,
      "uenum": upEnd ?? 0,
      "dsnum": downStart ?? 0,
      "denum": downEnd ?? 0,
    },callback: BaseCallback(
        onSuccess: (val){
          CreateBuildingIndexResponseBean bean =
          CreateBuildingIndexResponseBean.fromMap(val);
          if(bean != null && bean.success && bean.data != null){
            loading(false);
            VgEventBus.global.send(new RefreshDiyPageEvent());
            VgToastUtils.toast(AppMain.context, "操作成功");
            RouterUtils.pop(context);
          }else{
            VgToastUtils.toast(AppMain.context, "操作成功");
          }

        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///获取水牌详情
  void getBuildingIndexDetail(String id){
    if(StringUtils.isEmpty(id)){
      return;
    }
    String cacheKey = NetApi.BUILDING_INDEX_DETAIL + (UserRepository.getInstance().authId?? "")
        + id;
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取缓存水牌详情：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        BuildingIndexDetailResponseBean bean = BuildingIndexDetailResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            buildingIndexDetailValueNotifier?.value = bean?.data;
          }
          loading(false);
        }
        getBuildingDetailOnLine(id, cacheKey, bean);
      }else{
        getBuildingDetailOnLine(id, cacheKey, null);
      }
    });
  }

  void getBuildingDetailOnLine(String id, String cacheKey, BuildingIndexDetailResponseBean bean){
    VgHttpUtils.get(NetApi.BUILDING_INDEX_DETAIL,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          BuildingIndexDetailResponseBean bean =
          BuildingIndexDetailResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            //过滤playday为0的情况
            if(bean != null && bean.data != null){
              buildingIndexDetailValueNotifier?.value = bean?.data;
            }
          }
          loading(false);
          if(bean!=null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            print("缓存文件详情：" + cacheKey + "   " + json.encode(bean));
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          if(bean == null){
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }
        }
    ));
  }

  ///删除diy水牌
  void deleteBuildingIndex(BuildContext context, String id){
    if(StringUtils.isEmpty(id)){
      return;
    }
    loading(true,);
    VgHttpUtils.get(NetApi.DELETE_BUILDING_INDEX,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          RouterUtils.pop(context);
          VgEventBus.global.send(new RefreshDiyPageEvent(isDelete: true));
          VgEventBus.global.send(new UpdateDiyCenterInfoEvent());
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///更换水牌模板
  void changeBuildingIndexModule(BuildContext context, String buildingIndexId, String moduleId){
    if(StringUtils.isEmpty(buildingIndexId) || StringUtils.isEmpty(moduleId)){
      return;
    }
    loading(true,);
    VgHttpUtils.get(NetApi.BUILDING_INDEX_CHANGE_MODULE,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id": buildingIndexId ?? "",
      "syswid": moduleId ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshDiyPageEvent());
          loading(false);
          RouterUtils.pop(context, result: true);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  ///创建楼层企业
  void createFloorCompany(BuildContext context, String id, String company, String floorflg,
      String fnum, String hnum, bool needPop, {VoidCallback callback}){
    if(StringUtils.isEmpty(id)){
      return;
    }
    loading(true, msg: "正在创建");
    VgHttpUtils.get(NetApi.ADD_BUILDING_INDEX_FLOOR_COMPANY, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id":id ?? "",
      "company": company ?? "",
      "floorflg": floorflg ?? "",
      "fnum": fnum ?? "",
      "hnum": hnum ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgToastUtils.toast(AppMain.context, "创建成功");
          VgEventBus.global.send(new RefreshDiyPageEvent());
          if(needPop??false){
            RouterUtils.pop(context);
          }
          if(callback != null){
            callback.call();
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///编辑楼层企业
  void editFloorCompany(BuildContext context, String id, String company, String floorflg,
      String fnum, String hnum, bool needPop){
    if(StringUtils.isEmpty(id)){
      return;
    }
    loading(true, msg: "正在创建");
    VgHttpUtils.get(NetApi.EDIT_BUILDING_INDEX_FLOOR_COMPANY, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id":id ?? "",
      "company": company ?? "",
      "floorflg": floorflg ?? "",
      "fnum": fnum ?? "",
      "hnum": hnum ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgToastUtils.toast(AppMain.context, "编辑成功");
          VgEventBus.global.send(new RefreshDiyPageEvent());
          if(needPop??false){
            RouterUtils.pop(context);
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///删除楼层企业
  void deleteFloorCompany(BuildContext context, String id){
    if(StringUtils.isEmpty(id)){
      return;
    }
    loading(true,);
    VgHttpUtils.get(NetApi.DELETE_BUILDING_INDEX_FLOOR_COMPANY,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshDiyPageEvent());
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///楼层指示牌投放至终端
  void pushBuildingIndex(BuildContext context, String id, String hsns, VoidCallback callback){
    if(StringUtils.isEmpty(id)){
      return;
    }
    VgHudUtils.show(context, "设置中");
    VgHttpUtils.get(NetApi.BUILDING_INDEX_SET_TERMINAL, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id": id??"",
      "hsns":hsns ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshBuildingIndexTerminalSettingsEvent());
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "设置成功");
          callback.call();
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  void getTerminalList(String searchStr){
    VgHttpUtils.get(NetApi.BUILDING_INDEX_GET_TERMINAL, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsnname":searchStr ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          BuildingIndexTerminalListResponseBean bean =
          BuildingIndexTerminalListResponseBean.fromMap(val);
          if(!isStateDisposed){
            if(bean != null && bean.data != null){
              buildingIndexTerminalValueNotifier?.value = bean?.data;
              if(bean.data.hsnList != null && bean.data.hsnList.isNotEmpty){
                statusTypeValueNotifier?.value = null;
              }else{
                statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
              }
            }else{
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        },
        onError: (msg){
          loading(false);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  void updateDiyBuildingIndexPicUrl(BuildContext context, String id, String imagePath){
    loading(true, msg: "合成中");
    VgMatisseUploadUtils.uploadSingleImage(
        imagePath,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            VgHttpUtils.get(NetApi.UPDATE_BUILDING_INDEX_PIC, params: {
              "authId":UserRepository.getInstance().authId ?? "",
              "id":id ?? "",
              "picurl":netPic ?? "",
            },callback: BaseCallback(
                onSuccess: (val){
                  loading(false);
                  VgEventBus.global.send(new RefreshDiyPageEvent());
                  VgEventBus.global.send(new ChangeToDiyOrModulePageEvent(0));
                  VgHudUtils.hide(context);
                  RouterUtils.pop(context);
                  VgEventBus.global.send(new ShowSetModuleTypeBubbleEvent());
                  FileUtils.safeDeleteTemporaryFiles();
                },
                onError: (msg){
                  loading(false);
                  VgToastUtils.toast(AppMain.context, msg);
                  FileUtils.safeDeleteTemporaryFiles();
                }
            ));
          } else {
            VgToastUtils.toast(context, "图片上传失败");
            FileUtils.safeDeleteTemporaryFiles();
          }
        }, onError: (String msg) {
          loading(false);
          VgToastUtils.toast(context, msg);
          print("msg:" + msg);
          FileUtils.safeDeleteTemporaryFiles();
        },));
  }


  ///按楼层编辑企业
  void editCompanyByFloor(BuildContext context, String id, String fnum, String floorflg,
      String comList){
    if(StringUtils.isEmpty(id)){
      return;
    }
    loading(true, msg: "请稍后");
    VgHttpUtils.get(NetApi.EDIT_BUILDING_INDEX_COMPANY_BY_FLOOR, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "id":id ?? "",
      "fnum": fnum ?? "",
      "floorflg": floorflg ?? "",
      "comList": comList ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgToastUtils.toast(AppMain.context, "操作成功");
          VgEventBus.global.send(new RefreshDiyPageEvent());
          RouterUtils.pop(context, result: true);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///删除diy水牌
  void setModuleType(BuildContext context, String wbflg){
    if(StringUtils.isEmpty(wbflg)){
      return;
    }
    loading(true,);
    VgHttpUtils.get(NetApi.SET_BUILDING_INDEX_MODULE_TYPE,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "wbflg": wbflg ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  @override
  void onDisposed() {
    statusTypeValueNotifier?.dispose();
    buildingIndexDetailValueNotifier?.dispose();
    super.onDisposed();
  }
}
